<template>
  <div style="height: 100%">
    <zh-row>
      <zh-col :span="24">
        <zh-card shadow="hover"  mode="default" title="菜单树">
          <template #header>
            <zh-row>
              <zh-col :span="2" style="color: var(--el-color-primary)">
                <div style="line-height: 60px; height: 60px">
                  <SvgIcon name="ele-Menu" :size="24" />
                </div>
              </zh-col>
              <zh-col :span="22">
                <zh-select
                    placeholder="请选择所属应用"
                    label="有效状态"
                    v-model="state.appId"
                    :options="state.applicationList"
                    :fieldNames="{ label: 'appName', value: 'appId' }"
                ></zh-select>
              </zh-col>
            </zh-row>
          </template>
          <div>
            <zh-tree
                ref="treeRef"
                show-checkbox
                :height="`calc(100vh - 50px)`"
                :checkStrictly="false"
                :autoExpandParent="state.autoExpandParent"
                :default-expanded-keys="state.expandedKeys"
                :default-checked-keys="state.checkedKeys"
                :data="state.treeList"
                :props="{ children: 'children', label: 'title' }"
                node-key="key"
            >
            </zh-tree>
          </div>
        </zh-card>
      </zh-col>
    </zh-row>
  </div>
</template>

<script lang="ts" setup name="AppMenuTreeForm">
import { ElTree } from 'element-plus';
import {watch} from "vue";

//------------------接收传入参数(组件)-------------------
const props = defineProps({
  userId: {
    type: String,
    default: null,
    required: false,
  },
  roleId: {
    type: String,
    default: null,
    required: false,
  },
  type: {
    type: String,
  },
  modelValue: Boolean,
});
const emit = defineEmits(['update:modelValue']);

//------------------定义子组件---------------------------
const treeRef = ref<InstanceType<typeof ElTree>>();

//------------------内部变量定义-------------------------
const state = reactive({
  description: '路由功能管理',
  // 功能树
  expandedKeys: [],
  selectedKeys: [],
  searchValue: '',
  autoExpandParent: true,
  treeList: [] as any,
  checkedKeys: [],
  applicationList: [],
  appId: ""
});

//------------------定义调用方法-------------------------
function getApplicationList() {
  state.applicationList = [];
  $api.common.send
      .post("application0012", {type: '2',authStatus: '1',status: '1'}, 30000)
      .then((res) => {
        state.applicationList = res.result?.list
        if(state.applicationList.length > 0){
          state.appId = state.applicationList[0].appId;
          findRouterFuncTreeList(state.appId)
        }
      })
      .catch(() => {});
}
function loopExpandKey(data, keys, expandKeys) {
  let flag = false;
  data.forEach((item) => {
    let itemFlag = false;
    const myKey = item.key;
    keys.some((item) => {
      if (myKey === item) {
        itemFlag = true;
        return true;
      }
    });
    if (item.children) {
      const childFlag = loopExpandKey(item.children, keys, expandKeys);
      if (childFlag) {
        itemFlag = true;
      }
    }
    if (itemFlag) {
      flag = true;
      expandKeys.push(item.key);
    }
  });
  return flag;
}
function findRouterFuncTreeList(appId :String) {
  const params = {
    appId,
    roleId: props.roleId,
    userId: props.userId,
  };
  let funcCode = '';
  if(props.type === 'user'){
    funcCode = 'appmenu0025'
  }else {
    funcCode = 'appmenu0024'
  }
  setTimeout(() => {
    $api.common.send
        .post(funcCode, params, 30000)
        .then((res) => {
          const data = [...res.result.treeList];
          if (data) {
            state.treeList = data;
            state.checkedKeys = [];
            const expandedKeys = res.result.expandedKeys;
            const checkedKeys = res.result.checkedKeys;
            if (checkedKeys && checkedKeys.length > 0) {
              // 设置展开节点
              const expandedRouterFuncKeys = [];
              loopExpandKey(data, checkedKeys, expandedRouterFuncKeys);
              state.checkedKeys = checkedKeys;
              state.expandedKeys = expandedRouterFuncKeys;
            } else {
              state.expandedKeys = expandedKeys;
            }
            state.autoExpandParent = true;
          }
        })
        .catch(() => {});
  }, 50);
}

function getCheckedKeys() {
  return treeRef.value!.getCheckedKeys(false);
}

function saveAppRouter() {
  let funcCode = '';
  const params: any = {};
  if (props.type === 'user') {
    funcCode = 'user0040';
    params.userId = props.userId;
  } else if (props.type === 'role') {
    funcCode = 'role0023';
    params.roleId = props.roleId;
  }

  const checkedkeys: any = getCheckedKeys();

  if (Array.isArray(checkedkeys)) {
    params.objectIds = checkedkeys;
  } else {
    params.objectIds = checkedkeys.checked;
  }
  setTimeout(() => {
    $api.common.send
        .post(funcCode, params, 20000)
        .then(() => {
          $messageBox.success('授权成功', '提示');
          emit('update:modelValue', false);
        })
        .catch(() => {});
  }, 10);
}

//------------------初始化------------------------------
onMounted(() => {
  nextTick(() => {
    getApplicationList();
  });
});

watch(
    () => state.appId,
    () => {
      console.log(state.appId)
    }
);

//------------设置给父组件调用的数据/方法(组件)-----------
defineExpose({
  getCheckedKeys,
  saveAppRouter,
});
</script>
<style></style>